// miniprogram/pages/user/chatroom/chatroom.js
// 表情包相关东西
import EmojiDecoder from "../../../static/lib/EmojiDecoder";
import user from "../../../api/user"
import store from '../../../store/index'
import create from '../../../utils/create'

let emojiUrl = 'https://imgcache.qq.com/open/qcloud/tim/assets/emoji/';
let emojiMap = {
	'[么么哒]': 'emoji_3@2x.png',
	'[乒乓]': 'emoji_4@2x.png',
	'[便便]': 'emoji_5@2x.png',
	'[信封]': 'emoji_6@2x.png',
	'[偷笑]': 'emoji_7@2x.png',
	'[傲慢]': 'emoji_8@2x.png'
};


const app = getApp()
import IMService from '../../../static/lib/imservice.js';
Page({

	/**
	 * 页面的初始数据
	 */

	data: {
		files: [],
		fileNum: 10, // 接收到的文件的数量
		fileList: [], // 待选择的文件列表，可以是简历也可以是作品集
		title: '', // 文件选择列表的题目
		show: false, // 显示选择框
		content: '',
		messages: [],

		//默认为false展示输入框, 为true时显示录音按钮，点击录音，本来的文本输入框会变成“按下录音”的按钮
		recordVisible: false,

		//所有历史消息加载完成标识
		allHistoryLoaded: false,
		//定义表情列表
		emoji: {
			url: emojiUrl,
			map: emojiMap,
			show: false,
			decoder: new EmojiDecoder(emojiUrl, emojiMap),
		},
		more: {//更多按钮
			show: false
		},
		imService: null,
		friend: {
			name: '加载中...'
		},
		currentUser: {

		},
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		store.fileParams = options;
		this.getData(options)
		console.log(options)
	},
	getData: async function (params) {
		const id1 = params.id1 //这个是朋友的id
		const id2 = params.id2
		console.log(id1)
		console.log(id2)
		await user.getAvatar(id1).then(res => {
			console.log('id1的数据如下：')
			console.log(res);
			this.data.friend.uuid = res.data._openid
			this.data.friend.avatar = res.data.avatarUrl
			this.data.friend.name = res.data.nickName
		})
		await user.getAvatar(id2).then(res => {
			console.log('id2的数据如下：')
			console.log(res);
			this.data.currentUser.uuid = id2
			this.data.currentUser.avatar = res.data.avatarUrl
			this.data.currentUser.name = res.data.nickName
		})
		console.log(this.data.currentUser)
		console.log(this.data.friend)
		if (wx.im.getStatus() === 'disconnected') {
			app.globalData.imService = new IMService(wx.im);
			app.globalData.imService.connectIM(this.data.currentUser);
		}
		
		// 上面已经初始完基础信息了，friend就是消息发送给的那个人，currentUser就是自己

		let imService = app.globalData.imService;
		let currentUser = this.data.currentUser
		// let friend = imService.findFriendById(friendId);这里就直接从数据库获取到用户信息就行
		let friend = this.data.friend;
		let friendId = params.id1
		this.setData({
			friend: friend,
			imService: imService,
			currentUser: currentUser,
		}, () => {
			this.loadFile()
		});
		// 获取消息
		let messages = this.data.imService.getPrivateMessages(friendId);
		// 渲染表情与消息间隔5分钟显示时间
		this.renderMessages(messages);
		this.scrollToBottom();
		// 收到的消息设置为已读
		if (this.data.messages.length !== 0) {
			this.markPrivateMessageAsRead(friendId);
		}
		//传入监听器，收到一条私聊消息总是滚到到页面底部
		this.data.imService.onNewPrivateMessageReceive = (friendId, message) => {
			if (friendId === this.data.friend.uuid) {
				this.renderMessages(this.data.messages);
				this.scrollToBottom();
				// 如果是好友发送则清除未读消息
				this.markPrivateMessageAsRead(friendId);
			}
		};


	},
	onShow: function () {
		this.loadFile2();
	},
	onUnload() {
		//退出聊天页面之前，清空页面传入的监听器
		if (this.data.imService) {
			this.data.imService.onNewPrivateMessageReceive = (friendId, message) => { };
		}
	},
	onRecordStop(res) {
		// 发送语音
		let audioMessage = wx.im.createAudioMessage({
			to: {
				id: this.data.friend.uuid,
				type: wx.GoEasyIM.SCENE.PRIVATE,
				data: { name: this.data.friend.name, avatar: this.data.friend.avatar }
			},
			file: res.detail,
			onProgress: function (progress) {
				console.log(progress)
			}
		});
		this.sendMessage(audioMessage);
	},
	sendTextMessage() {
		// 发送文本与表情
		if (this.data.content.trim() !== '') {
			let textMessage = wx.im.createTextMessage({
				text: this.data.content,
				to: {
					id: this.data.friend.uuid,
					type: wx.GoEasyIM.SCENE.PRIVATE,
					data: { name: this.data.friend.name, avatar: this.data.friend.avatar }
				}
			});
			this.sendMessage(textMessage);
		}
		this.setData({
			content: ""
		});
	},
	sendImage() {
		// 发送图片
		let self = this;
		wx.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success(res) {
				let imageMessage = wx.im.createImageMessage({
					to: {
						id: self.data.friend.uuid,
						type: wx.GoEasyIM.SCENE.PRIVATE,
						data: { name: self.data.friend.name, avatar: self.data.friend.avatar }
					},
					file: res,
					onProgress: function (progress) {
						console.log(progress)
					}
				});
				self.sendMessage(imageMessage);
			}
		});
	},
	sendVideo() {
		// 发送视频
		let self = this;
		wx.chooseVideo({
			sourceType: ['album', 'camera'],
			maxDuration: 60,
			camera: 'back',
			success(res) {
				let videoMessage = wx.im.createVideoMessage({
					to: {
						id: self.data.friend.uuid,
						type: wx.GoEasyIM.SCENE.PRIVATE,
						data: { name: self.data.friend.name, avatar: self.data.friend.avatar }
					},
					file: res,
					onProgress: function (progress) {
						console.log(progress)
					}
				});
				self.sendMessage(videoMessage);
			}
		})
	},
	sendMessage(message) {
		let self = this;
		this.data.messages.push(message);
		this.renderMessages(this.data.messages);
		this.scrollToBottom();
		let promise = wx.im.sendMessage(message);
		promise.then((res) => {
			console.log('发送消息成功');
			self.renderMessages(self.data.messages);
		})
			.catch(e => {
				console.log('发送失败', e)
			});
	},
	onPullDownRefresh() {
		this.loadMoreHistoryMessage();
	},
	loadMoreHistoryMessage() {
		//历史消息
		let friendId = this.data.friend.uuid;
		let lastMessageTimeStamp = Date.now();
		let lastMessage = this.data.messages[0];
		if (lastMessage) {
			lastMessageTimeStamp = lastMessage.timestamp;
		}
		let currentLength = this.data.messages.length;
		let promise = app.globalData.imService.loadPrivateHistoryMessage(friendId, lastMessageTimeStamp);
		promise.then(messages => {
			if (messages.length === currentLength) {
				this.setData({
					allHistoryLoaded: true
				})
			}
			this.renderMessages(this.data.messages);
			wx.stopPullDownRefresh();
		}).catch(e => {
			console.log(e)
			wx.stopPullDownRefresh();
		})
	},
	renderMessages(messages) {
		messages.forEach((message, index) => {
			if (index === 0) {
				// 当页面只有一条消息时，显示发送时间
				message.showTime = app.formatDate(message.timestamp);
			} else {
				// 当前消息与上条消息的发送时间进行比对，超过5分钟则显示当前消息的发送时间
				if (message.timestamp - messages[index - 1].timestamp > 5 * 60 * 1000) {
					message.showTime = app.formatDate(message.timestamp);
				}
			}
			if (message.type === 'text') {
				// 渲染表情与文本消息
				let text = this.data.emoji.decoder.decode(message.payload.text);
				message.node = text;
			}
		});
		this.setData({
			messages: messages
		});
	},

	// 把信息标注为已读
	markPrivateMessageAsRead(friendId) {
		wx.im.markPrivateMessageAsRead(friendId)
			.then(() => {
				console.log('标记为已读成功')
			})
			.catch(e => {
				console.log('标记为已读失败', e)
			})
	},

	// 这个主要是对录音的信息进行监听
	setContent(e) {
		// 监听输入的消息
		let content = e.detail.value;
		this.setData({
			content: content
		});
	},
	switchAudioKeyboard() {
		// 语音录制按钮和键盘输入的切换
		this.setData({
			recordVisible: !this.data.recordVisible
		});
		if (this.data.more.show || this.data.emoji.show) {
			this.setData({
				["more.show"]: false,
				["emoji.show"]: false
			});
		}
		if (this.data.recordVisible) {
			// 录音授权
			wx.authorize({
				scope: 'scope.record',
				success() { }
			});
		}
	},
	playVideo(e) {
		//播放视频
		this.selectComponent("#videoPlayer").play({
			url: e.currentTarget.dataset.url,
			duration: e.currentTarget.dataset.duration
		})
	},
	previewImage(event) {
		// 预览图片
		let imagesUrl = [event.currentTarget.dataset.src];
		wx.previewImage({
			urls: imagesUrl // 需要预览的图片http链接列表
		})
	},
	selectEmoji(e) {
		// 选择表情
		let emojiKey = e.currentTarget.dataset.emojikey;
		emojiKey = this.data.content + emojiKey;
		this.setData({
			content: emojiKey
		});
	},
	messageInputFocusin() {
		this.setData({
			["more.show"]: false,
			["emoji.show"]: false
		});
	},
	showEmoji() {
		this.setData({
			["emoji.show"]: true,
			["more.show"]: false,
			recordVisible: false
		});
		// 关闭手机键盘
		wx.hideKeyboard();
	},
	showMore() {
		this.setData({
			["more.show"]: true,
			["emoji.show"]: false
		});
		// 关闭手机键盘
		wx.hideKeyboard();
	},
	scrollToBottom() { // 滑动到最底部
		wx.pageScrollTo({
			scrollTop: 200000,
			duration: 10
		})
	},
	// 跳转到接收的文件页面
	toResume: function () {
		var id = this.data.friend.uuid
		var files = this.data.files
		var name = this.data.friend.name;
		console.log(files);
		wx.navigateTo({
			url: '../fileList/fileList?files=' + JSON.stringify(files) + '&name=' + name,
		})
	},
	// 发送简历
	tapResume() {
		var resume = store.data.user.resume
		console.log(resume);
		this.setData({
			show: true,
			fileList: resume,
			title: '选择发送的简历'
		})
	},
	// 发送作品集
	tapWork() {
		var works = store.data.user.works
		this.setData({
			show: true,
			fileList: works,
			title: '选择发送的作品集'
		})
	},
	loadFile: async function (e) {
		const that = this
		return new Promise((reslove, reject) => {
			var file = []
			var friList = []
			var friendID = this.data.friend.uuid
			console.log(friendID)
			console.log(store.data.user.yourWorks)
			console.log(store.data.user.yourResume);

			store.data.user.yourWorks.forEach(item => {
				if(item.file) {
					friList.push(item)
				}
			})
			store.data.user.yourResume.forEach(item => {
				if(item.file) {
					friList.push(item)
				}
			})
			// friList.push(...store.data.user.yourWorks)
			// friList.push(...store.data.user.yourResume)
			console.log(friList)
			for (var i = 0; i < friList.length; i++) {
				file.push(new Promise((reslove, reject) => {
					console.log("111")
					var op = friList[i].Myopenid
					if (op == friendID) {
						//console.log("222")
						//  console.log(friList[i].file)
						that.data.files.push(friList[i].file)
						that.setData({
							files: that.data.files
						}, () => {
							console.log(that.data.files)
						})
						reslove(friList[i].file)
					}
				}))
			}
			Promise.all(file).then(res => {
				reslove(res)
			})
		})
	},

	loadFile2: async function (e) {
		const that = this
		return new Promise((reslove, reject) => {
			var file = []
			var friList = []
			var friendID = this.data.friend.uuid
			console.log(friendID)
			console.log(store.data.user.yourWorks)
			console.log(store.data.user.yourResume);

			store.data.user.yourWorks.forEach(item => {
				if(item.file) {
					friList.push(item)
				}
			})
			store.data.user.yourResume.forEach(item => {
				if(item.file) {
					friList.push(item)
				}
			})
			// friList.push(...store.data.user.yourWorks)
			// friList.push(...store.data.user.yourResume)
			console.log(friList);
			that.data.files = [];
			for (var i = 0; i < friList.length; i++) {
				file.push(new Promise((reslove, reject) => {
					console.log("111")
					var op = friList[i].Myopenid
					if (op == friendID) {
						//console.log("222")
						//  console.log(friList[i].file)
						that.data.files.push(friList[i].file)
						that.setData({
							files: that.data.files
						}, () => {
							console.log(that.data.files)
						})
						reslove(friList[i].file)
					}
				}))
			}
			Promise.all(file).then(res => {
				reslove(res)
			})
		})
	},
})